<?php
/**
 * Created by PhpStorm.
 * User: edmmss
 * Date: 2021/9/27
 * Time: 16:52
 */

namespace Edmmss\Common;

class SerializerPack
{
    const JSON_OPTIONS = 320;
    const SERIALIZER_TYPE_BASE = 1;

    /**
     * 传输加密
     *
     * @date   2021/9/27
     * @param $data
     * @param $serializerType
     * @param $serialId
     * @param int $id
     * @return string
     * @author edmmss
     */
    public static function encode($data, $serializerType, $serialId, $id = 0)
    {
        $data = json_encode($data, self::JSON_OPTIONS);

        return Pack::pack($data, $serializerType, $serialId, $id) . $data;
    }

    /**
     * 传输解密
     *
     * @date   2021/9/27
     * @param $data
     * @return array|false
     * @author edmmss
     */
    public static function decode($data)
    {
        $header = Pack::unpack(substr($data, 0, Pack::PACK_HEADER_SIZE));
        if (!$header || !isset($header['serializerType'])) {
            return false;
        }

        $data = substr($data, Pack::PACK_HEADER_SIZE);
        $returnData = json_decode($data, true);
        if ($returnData) {
            return [
                'header' => $header,
                'data'   => $returnData,
            ];
        } else {
            return false;
        }
    }
}